<template>
<div class="container">
  <el-upload ref="upload" class="avatar-uploader" :before-upload="beforeAvatarUpload" action="#"
             :http-request="uploadFile" :auto-upload="false" multiple list-type="picture-card" :file-list="fileList"
             :on-change="fileChange">
    <el-icon>
      <Plus />
    </el-icon>
    <template #file="{ file }">
      <img :src="file.url" alt="" />
    </template>

  </el-upload>
  <el-radio-group title="性别" v-model="gender" style="width: 600px" size="large">
    <el-radio-button label="1">公</el-radio-button>
    <el-radio-button label="0">母</el-radio-button>
  </el-radio-group>

  <el-input placeholder="请输入宠物名字" v-model="name" label="name"></el-input>
  <el-input placeholder="请输入宠物品种" v-model="variety" label="variety"></el-input>
  <el-input placeholder="请输入宠物年龄" v-model="age" label="age"></el-input>
  <el-input placeholder="请输入宠物体重" v-model="weight" label="weight"></el-input>
  <el-button type="info" @click="cancel">取消</el-button>
  <el-button type="primary" @click="handleUpdateAvatar">确定</el-button>
</div>
</template>

<script>
import axios from "axios";
export default {
  name: "PetAdd",
  data() {
    return {
      fileList: [],
      name: '',
      variety: '',
      gender: '',
      age: '',
      weight: '',
    };
  },
  methods: {
    // 自定义上传图片方法,参数必须为params
    uploadFile(params) {
      const file = params.file;
      var forms = new FormData();
      // 我这里需要将更新时间和uid同时传给后端，后端使用对象接收，所以没有设置content-type
      // 如果你只传file，要设置axios中headers的content-type为：multipart/form-data
      forms.append("file", file);
      forms.append("name", this.name);
      forms.append("gender", this.gender);
      forms.append("age", this.age);
      forms.append("variety", this.variety);
      forms.append("weight", this.weight);
      axios.post("http://localhost:8088/pet/add",forms,{withCredentials:true})
          .then(res => {
            if (res.data.code == "200") {
              this.$message({
                message: '上传成功',
                type: 'success'
              })
              this.$router.push('/PetPage')
            } else {
              this.$message({
                message: '上传失败',
                type: 'error'
              })
            }
          }).catch(err => {
        console.log("上传文件时发生错误: " + err);
      })
    },
    // 上传图片时检查
    beforeAvatarUpload(file) {
      //允许的图片类型
      const imgType = (file.type === 'image/jpeg') || (file.type === 'image/png') || (file.type === 'image/gif');
      //文件大小3M
      const imgLimit= (file.size / 1024 / 1024) < 3;
      if (!imgType) {
        this.$message.error("只允许jpg、png、gif格式的图片");
        return false;
      }
      if (!imgLimit) {
        this.$message.error("上传的图片大小不能超过3MB");
        return false;
      }
      console.log("检查通过");
      return true;
    },
    //文件改变时的钩子函数,只能上传一张，选中后会覆盖掉之前的图片，
    fileChange(file, fileList) {
      //this.file表示上一张被选中的图片，file.raw表示当前选中的图片
      this.file = file.raw;
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]];
      }
    },
    // 确认修改头像
    handleUpdateAvatar() {
      this.$refs['upload'].submit();
      this.avatarDialogVisible = false;
      this.$refs['upload'].clearFiles();
    },
    // 取消上传头像
    cancel() {
      this.avatarDialogVisible = false;
      this.$refs['upload'].clearFiles();
      this.$router.push('/petPage')
    },
  }

}
</script>

<style scoped>
.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader {
  display: inline-block;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
  position: relative;
}

.avatar-uploader .el-upload {
  width: 100%;
  height: 100%;
}

.avatar-uploader .el-upload-list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
}

.avatar-uploader .el-upload-list .el-upload-list__item {
  width: 100px;
  height: 100px;
  margin-right: 10px;
  margin-bottom: 10px;
  position: relative;
}

.avatar-uploader .el-upload-list .el-upload-list__item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-uploader .el-upload-list .el-upload-list__item .el-icon-close {
  position: absolute;
  top: 5px;
  right: 5px;
  cursor: pointer;
}

.el-input {
  margin-top: 10px;
}

.el-button {
  margin-top: 20px;
}

</style>